import { observer } from 'mobx-react'
import { useState, useEffect } from 'react'
import type { PopconfirmProps } from 'antd'
import { Input, Select, Button, Table, DatePicker, Popconfirm, message } from 'antd'
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import dayjs from 'dayjs'
import { getAppVersionList } from '@/apis/appVersionManagement'
import { useNavigate } from 'react-router-dom'
import { getInMgList } from '@/apis/internationalMg'

const { RangePicker } = DatePicker

// 列表数据类型
interface DataType {
  key: string;
  keyName: string;
  cn: string;
  en: string;
  status: string;
  operator: string;
  operationTime: string;
}

// 定义筛选表单的接口
interface FilterForm {
  keyName: string;
  cn: string;
  status: string | null;
  operator: string;
  dateRange: [string, string] | null;
}

// 初始化表单状态
const initialFilterForm: FilterForm = {
  keyName: '',
  cn: '',
  status: '-1',
  operator: '',
  dateRange: null,
}

const AppVersionManagement: React.FC = () => {
  const [filterForm, setFilterForm] = useState<FilterForm>(initialFilterForm)
  const [data, setData] = useState<DataType[]>([])
  const [loading, setLoading] = useState(false)
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const navigate = useNavigate()

  // 获取列表数据
  const fetchData = async (params = {}) => {
    try {
      setLoading(true)
      const response = await getInMgList({
        ...filterForm,
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      })
      console.log(response, 'response----');
      const { data } = response
      if (data.code === 200) {
        // 为每条数据添加唯一的 key
        const listWithKeys = data.list.map((item: any) => ({
          ...item,
          key: item.id.toString()
        }))
        setData(listWithKeys)
        setPagination(prev => ({
          ...prev,
          total: data.total
        }))
      } else {
        message.error(data.message || '获取数据失败')
      }
    } catch (error) {
      console.error('获取数据失败:', error)
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  // 页面初始化时获取数据
  useEffect(() => {
    fetchData()
  }, [])

  // 处理表单字段变化
  const handleFormChange = (field: keyof FilterForm, value: any) => {
    setFilterForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 搜索事件处理
  const handleSearch = async () => {
    try {
      const { dateRange, ...rest } = filterForm
      const params = {
        ...rest,
        current: 1,
        pageSize: pagination.pageSize,
        startTime: dateRange?.[0] || undefined,
        endTime: dateRange?.[1] || undefined,
      }

      setPagination(prev => ({ ...prev, current: 1 }))
      await fetchData(params)
    } catch (error) {
      console.error('查询失败:', error)
      message.error('查询失败')
    }
  }

  // 重置表单事件处理
  const handleReset = () => {
    setFilterForm(initialFilterForm)
    setPagination(prev => ({ ...prev, current: 1 }))
    fetchData({
      ...initialFilterForm,
      current: 1,
      pageSize: pagination.pageSize
    })
  }

  // 处理表格分页、排序、筛选变化
  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize
    }))
    fetchData({
      current: newPagination.current,
      pageSize: newPagination.pageSize
    })
  }
  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e)
    message.success('点击确定')
  }
  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e)
    message.error('点击取消')
  }
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      // 序号自增
      render: (_, record, index) => index + 1,
    },
    {
      title: '名称Key',
      dataIndex: 'keyName',
      key: 'keyName',
    },
    {
      title: '中文',
      dataIndex: 'cn',
      key: 'cn',
    },
    {
      title: '英文',
      dataIndex: 'en',
      key: 'en',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
    },
    {
      title: '操作时间',
      dataIndex: 'operationTime',
      key: 'operationTime',
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (record) => (
        <div className='table-cell-actions'>
          <Button type="link" onClick={() => handleEdit(record)}>修改</Button>
          <Popconfirm
            title="提示"
            description="是否禁用？"
            onConfirm={confirm}
            onCancel={cancel}
            okText="是的"
            cancelText="取消"
          >
            <Button type="link">禁用</Button>
          </Popconfirm>
          <Button type="link" disabled>删除</Button>
        </div>
      ),
    },
  ]
  const statusOptions = [
    {
      label: '全部',
      value: '-1',
    },
    {
      label: '正常',
      value: '0',
    },
    {
      label: '禁用',
      value: '1',
    },
  ]
  const handleAdd = () => {
    navigate('/setting/internationalMg/add')
  }
  const handleRefresh = () => {
    message.success('刷新缓存完成')
  }
  const handleEdit = (record: DataType) => {
    navigate('/setting/internationalMg/add', { state: { record } })
  }
  return (
    <div className="app-container">
      <div className="filterForm">
        <div className="form">
          <div className="field">
            <div className="label">名称Key</div>
            <div className="value">
              <Input
                allowClear
                placeholder="请输入名称Key"
                value={filterForm.keyName}
                onChange={e => handleFormChange('keyName', e.target.value)}
                suffix={<span />}
              />
            </div>
          </div>
          <div className="field">
            <div className="label">中文</div>
            <div className="value">
              <Input
                allowClear
                placeholder="请输入中文"
                value={filterForm.cn}
                onChange={e => handleFormChange('cn', e.target.value)}
                suffix={<span />}
              />
            </div>
          </div>
          <div className="field">
            <div className="label">状态</div>
            <div className="value">
              <Select
                placeholder="请选择版本号"
                style={{ width: '100%' }}
                value={filterForm.status}
                defaultValue="-1"
                onChange={value => handleFormChange('status', value)}
                options={statusOptions}
              />
            </div>
          </div>
          <div className="field">
            <div className="label">操作人</div>
            <div className="value">
              <Input 
                placeholder="请输入操作人账号"
                value={filterForm.operator}
                onChange={e => handleFormChange('operator', e.target.value)}
                suffix={<span />}
              />
            </div>
          </div>
          <div className="field">
            <div className="label">操作时间</div>
            <div className="value">
              <RangePicker 
                style={{ width: '100%' }}
                value={filterForm.dateRange ? [
                  dayjs(filterForm.dateRange[0]),
                  dayjs(filterForm.dateRange[1])
                ] : null}
                onChange={(dates, dateStrings) => 
                  handleFormChange('dateRange', dates ? dateStrings : null)
                }
              />
            </div>
          </div>
        </div>
        <div className="rightAction">
          <Button type="primary" onClick={handleSearch}>
            <SearchOutlined />
            查询
          </Button>
          <Button onClick={handleReset}>
            <ReloadOutlined />
            重置
          </Button>
        </div>
      </div>

      <div className="table-operations">
        <Button type="primary" onClick={handleAdd}>+ 新增</Button>
        <Button onClick={handleRefresh}>刷新缓存</Button>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
        loading={loading}
        onChange={handleTableChange}
      />
    </div>
  )
}

export default observer(AppVersionManagement)